package edu.ynu.e_platform.common.dao;

import com.sun.istack.Nullable;
import edu.ynu.e_platform.common.entity.LogicEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @author manwen Yang
 */
@NoRepositoryBean
public interface LogicDAO<T extends LogicEntity, ID extends Serializable> extends JpaRepository<T, ID> {

    /**
    * 实现逻辑删除,将isDeleted置为1，即表示逻辑删除
    * */
    @Override
    @Query(value =
            "update #{#entityName} e " +
                    "set e.isDeleted =1, e.deletedTime = current_timestamp " +
                    "where e.id = ?1 and e.isDeleted = 0")
    @Transactional
    @Modifying
    void deleteById(ID id);

    /**
     * 实现逻辑删除
     * */
    @Override
    @Transactional
    default void delete(T entity) {
        deleteById((ID)entity.getId());
    }


    @Override
    @Transactional
    default void deleteAll(Iterable<? extends T> entities){
        entities.forEach(entity -> deleteById((ID) entity.getId()));
    }

    @Override
    @Transactional
    default void deleteAllById(Iterable<? extends ID> ids){
        ids.forEach(id->deleteById(id));
    }

    @Override
    @Query(value = "update #{#entityName} e set e.isDeleted =1, e.deletedTime = current_timestamp where e.isDeleted = 0")
    @Transactional
    @Modifying
    void deleteAll();

    @Override
    @Transactional
    default void deleteAllByIdInBatch(Iterable<ID> ids){
        ids.forEach(id->deleteById(id));
    }

    @Override
    @Transactional
    default void deleteAllInBatch(Iterable<T> entities){
        entities.forEach(entity -> deleteById((ID) entity.getId()));
    }

    @Override
    @Transactional
    default void deleteAllInBatch(){
        deleteAll();
    }

    /**
     * 返回未删除的实体个数
     * */
    @Override
    @Transactional(readOnly = true)
    @Query("select count(e) from #{#entityName} e where e.isDeleted = 0")
    long count();
}
